<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Chat extends Public_Controller {

	public function __construct()
	{
  		parent::Public_Controller();
		$this->load->library('form_validation');
		$this->lang->load('chat');
		$this->load->config('language');
		$this->load->config('chat');
		
		$this->load->library('chat/common_lib');
		$this->load->library('chat/chat_lib');
		$this->load->library('chat/operator_lib');
		$this->load->library('chat/groups_lib');
		$this->load->library('chat/expand_lib');
	}
	public function to($url_thread = NULL, $url_token = NULL, $url_level = NULL, $url_groupid = NULL)
	{
		if( !isset($url_thread) || !isset($url_token) ) {
	
			$thread = NULL;
			$sess_threadid = $this->session->userdata('threadid');
			if(!empty($sess_threadid) ) {
				$thread = $this->chat_lib->reopen_thread($sess_threadid);
			}
		}
		$groupid = "";
		$groupname = "";
		/* if( !isset($thread)) {
			if($this->config->item('enablegroups') == '1') {
				$groupid = $url_groupid;
				if($groupid) {
					$group = $this->groups_lib->group_by_id($groupid);
					if(!$group) {
						$groupid = "";
					} else {
						$groupname = $this->groups_lib->get_group_name($group);
					}
				}
			}
		} */	
		
		$visitor = $this->chat_lib->visitor_from_request();
		
		$survey = $this->input->post('survey');
		if(!empty($survey) && $survey == 'on') {
			/* $firstmessage = getparam("message");
			$info = $this->input->post('info');
			$email = $this->input->post('email');
			$referrer = urldecode(getparam("referrer"));
		
			if($settings['usercanchangename'] == "1" && isset($_POST['name'])) {
				$newname = getparam("name");
				if($newname != $visitor['name']) {
					$data = strtr(base64_encode(myiconv($webim_encoding,"utf-8",$newname)), '+/=', '-_,');
					setcookie($namecookie, $data, time()+60*60*24*365);
					$visitor['name'] = $newname;
				}
			} */
		} else {
			$firstmessage = NULL;
			$info = $this->input->post('info');
			$email = $this->input->post('email');
			$referrer = isset($_GET['url']) ? $_GET['url'] :
			(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "");
			if(isset($_GET['referrer']) && $_GET['referrer']) {
				$referrer .= "\n".$_GET['referrer'];
			}
		}
		
		if(!$this->operator_lib->has_online_operators($groupid)) {
			echo 'no operator<br/>';
			exit;
		}
		
		$remoteHost = $this->chat_lib->get_remote_host();
		$userbrowser = $_SERVER['HTTP_USER_AGENT'];
		
		if(!$this->chat_lib->check_connections_from_remote($remoteHost)) {
			die("number of connections from your IP is exceeded, try again later");
		}
		$current_locale = 'en';
		$thread = $this->chat_lib->create_thread($groupid,$visitor['name'], $remoteHost, $referrer,$current_locale,$visitor['id'], $userbrowser,$this->chat_lib->state_loading);

		$this->session->set_userdata('threadid', $thread['threadid']);
		
		if( $referrer ) {
			$this->chat_lib->post_message_($thread['threadid'],$this->chat_lib->kind_for_agent,sprintf(lang('chat.came.from'), $referrer));
		}
		$this->chat_lib->post_message_($thread['threadid'],$this->chat_lib->kind_info,lang('chat.wait'));
		if($email) {
			$this->chat_lib->post_message_($thread['threadid'],$this->chat_lib->kind_for_agent,sprintf(lang('chat.visitor.email'), $email));
		}
		if($info) {
			$this->chat_lib->post_message_($thread['threadid'],$this->chat_lib->kind_for_agent,sprintf(lang('chat.visitor.info'), $info));
		}
		if(isset($firstmessage)) {
			$postedid = $this->chat_lib->post_message_($thread['threadid'],$this->chat_lib->kind_user,$firstmessage,$visitor['name']);
			$this->chat_lib->commit_thread( $thread['threadid'], array('shownmessageid' => $postedid));
		}
		$threadid = $thread['threadid'];
		$token = $thread['ltoken'];
// 		$level = $this->chat_lib->get_remote_level($_SERVER['HTTP_USER_AGENT']);
		redirect(site_url('chat/begin/'. $threadid. '/'. $token));
// 		redirect(site_url('chat/begin/'. $threadid. '/'. $token. '/'. $level. '/'. $chatstyle));
	}
	public function begin($threadid, $token, $level = 'ajaxed', $chatstyle = 'default')
	{
		$thread = $this->chat_lib->thread_by_id_($threadid);
		if( !$thread || !isset($thread['ltoken']) || $token != $thread['ltoken'] ) {
			die("wrong thread");
		}
		
		$page = array();
		$page['agent'] = false;
		$page['user'] = true;
		$page['canpost'] = true;
		$nameisset = lang("chat.default.username") != $thread['userName'];
		$page['displ1'] = $nameisset ? "none" : "inline";
		$page['displ2'] = $nameisset ? "inline" : "none";
		$page['level'] = $level;
		$page['ct_chatThreadId'] = $thread['threadid'];
		$page['ct_token'] = $thread['ltoken'];
		$page['ct_user_name'] = htmlspecialchars($thread['userName']);
		$page['canChangeName'] = $this->config->item('usercanchangename', 'chat') == "1";
		$page['chat_title'] =  $this->config->item('chattitle', 'chat');
		
		$page['ct_company_name'] = $this->config->item('title', 'chat');
		$page['ct_company_chatLogoURL'] = $this->config->item('logo', 'chat');
		$page['webimHost'] = $this->config->item('hosturl', 'chat');
		
		if ($this->config->item('sendmessagekey', 'chat') == 'enter') {
			$page['send_shortcut'] = "Enter";
			$page['ignorectrl'] = 1;
		} else {
			$page['send_shortcut'] = $this->chat_lib->is_mac_opera() ? "&#8984;-Enter" : "Ctrl-Enter";
			$page['ignorectrl'] = 0;
		}
		
		$params = "thread=" . $thread['threadid'] . "&amp;token=" . $thread['ltoken'];
		
		$page['isOpera95'] = $this->chat_lib->is_agent_opera95();
		$page['neediframesrc'] = $this->chat_lib->needsFramesrc();
		
		$page['frequency'] = $this->config->item('updatefrequency_chat', 'chat');
		$this->template->set('layout', 'chat')->load('chat', $page);
	}
	public function get()
	{
		$act = $this->input->post('act');
		$token = $this->input->post('token');
		$threadid = $this->input->post('thread');
		$isuser = $this->input->post('user');
		$outformat = $this->input->post('html');
		$istyping = $this->input->post('typed');
		$lastid = $this->input->post('lastid');
		
		$isuser = 'true' == $isuser? TRUE: FALSE;
		$istyping = 1 == $istyping? 1: 0;
		
		$thread = $this->chat_lib->thread_by_id_($threadid);
		
		if( !$thread || !isset($thread['ltoken']) || $token != $thread['ltoken'] ) {
			die("wrong thread");
		}
		$this->chat_lib->ping_thread($thread, $isuser,$istyping);
		
		if( !$isuser && $act != "rename" ) {
			$this->load->model('chat/operator_model', 'operator_m');
			$operator = $this->operator_lib->check_login();
// 			$operator = $this->operator_m->check_login();
			$this->chat_lib->check_for_reassign($thread,$operator);
		} 
		$outformat = empty($outformat)? 'xml':$outformat;
		if( $act == "refresh" ) {
			$this->chat_lib->print_thread_messages($thread, $token, $lastid, $isuser,$outformat, $isuser ? null : $operator['operatorid']);
			exit;
		} else if( $act == "post" ) {
			$lastid = $this->input->post('lastid');
			$message = $this->input->post('message');
		
			$kind = $isuser ? $this->chat_lib->kind_user : $this->chat_lib->kind_agent;
			$from = $isuser ? $thread['userName'] : $thread['agentName'];
		
			if(!$isuser && $operator['operatorid'] != $thread['agentId']) {
				show_error("cannot send");
			}
		
			$postedid = $this->chat_lib->post_message_($threadid,$kind,$message, $from,null,$isuser ? null : $operator['operatorid'] );
			if($isuser && $thread["shownmessageid"] == 0) {
				$this->chat_lib->commit_thread( $thread['threadid'], array('shownmessageid' => $postedid));
			}
			$this->chat_lib->print_thread_messages($thread, $token, $lastid, $isuser, $outformat, $isuser ? null : $operator['operatorid']);
			exit;
		
		} else if( $act == "ping" ) {
			$this->show_ok_result("ping");
		
		} else if( $act == "close" ) {
		
			if( $isuser || $thread['agentId'] == $operator['operatorid']) {
				$this->chat_lib->close_thread($thread, $isuser);
			}
			$this->show_ok_result("closed");
		
		}
	}
	function alive()
	{
		$this->chat_lib->notify_operator_alive(1, 0);
	}
	
	function show_ok_result($resid) {
		$this->common_lib->start_xml_output();
		echo "<$resid></$resid>";
		exit;
	}
	function show_error($message) {
		$this->common_lib->start_xml_output();
		echo "<error><descr>$message</descr></error>";
		exit;
	}
	
/*	public function index()
	{
		$handle = @fopen(FCPATH. "properties", "r");
		if ($handle) {
		    while (!feof($handle)) {
		        $buffer = fgets($handle, 4096);
		        $info = explode("=", $buffer, 2);
//		        $lang['settings_save_success']
		        echo "\$lang['". trim($info[0]). "']=". "\"". trim($info[1]). "\";". '<br />';
		    }
		    fclose($handle);
		}
		
	}*/
}